import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_xc/dao/home_dao.dart';
import 'dart:convert';
import 'package:flutter_xc/model/home_model.dart';
import 'package:flutter_xc/pages/search_page.dart';
import 'package:flutter_xc/util/navigator_util.dart';
import 'package:flutter_xc/widget/grid_nav.dart';
import 'package:flutter_xc/widget/load_container.dart';
import 'package:flutter_xc/widget/local_nav.dart';
import 'package:flutter_xc/widget/sales_box.dart';
import 'package:flutter_xc/widget/search_bar.dart';
import 'package:flutter_xc/widget/sub_nav.dart';
// 最大滚动距离 显隐
const APPBAR_SCROLL_MAX_OFFSET = 100;
const SEARCH_BAR_DEFAULT_TEXT = '网红打卡地 景点 酒店 美食';
class HomePage extends StatefulWidget {
  /// 重写 createState 方法 并返回一个
  /// __TabNavigatorState类型的
  @override
  _HomePageState createState() => _HomePageState();
}

// 实现一个State,
class _HomePageState extends State<HomePage> {
  // appbar的透明度
  double _appBarAlpha = 0.0;
  // 数据请求的结果
  String _resultString = "";

  // local的数据
  List<CommonModel> localNav = [];
  GridNavModel gridNav;
  List<CommonModel> subNav = [];
  List<CommonModel> bannerList = [];
  SalesBoxModel salesBox;


  bool _loading = true;
  // 页面滚动 修改appbar的显示隐藏
  _scroll(offset) {
    double alpha = offset / APPBAR_SCROLL_MAX_OFFSET;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      _appBarAlpha = alpha;
    });
  }

  // 加载数据的第一种写法
  /*
    _loadData() {
      HomeDao.fetch().then((res) {
        setState(() {
          _resultString = json.encode(res);
        });
      }).catchError((e) {
        setState(() {
          _resultString = e.toString();
        });
      });
    }
   */

  // 加载数据的第二种写法
  Future<Null> _loadData() async {
    print('load data');
    try {
      HomeModel model = await HomeDao.fetch();
      setState(() {
        localNav = model.localNavList;
        gridNav = model.gridNav;
        subNav = model.subNavList;
        salesBox = model.salesBox;
        bannerList = model.bannerList;
        _loading = false;
        _resultString = json.encode(model.gridNav);
        print(_resultString);
      });
    } catch (e) {
      setState(() {
        _loading = false;
//        _resultString = e.toString();
        print(e);
      });
    }
    return null;
  }

  // 生命周期之初始化
  @override
  void initState() {
    super.initState();
    _loadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color(0xfff2f2f2),
        body: LoadingContainer(
          loading: _loading,
          child: Stack( // 层叠样式, 后面的在前面的之上
            children: <Widget>[
              MediaQuery.removePadding( // 移除listview自动适配的顶部padding
                  removeTop: true,
                  context: context,
                  child: RefreshIndicator(
                    onRefresh: _loadData,
                    child: NotificationListener( // 滚动监听
                      onNotification: (scrollNotification) {
                        if (scrollNotification is ScrollUpdateNotification
                            && scrollNotification.depth ==
                                0) { // 包裹的层级为第一层的时候滚动的监听
                          // 滚动,并且是列表滚动的时候,触发
                          _scroll(scrollNotification.metrics.pixels);
                        }
                        return true;
                      },
                      child: _listView,
                    ),
                  )
              ),
              _appBar,
            ],
          ),
        )
    );
  }

  Widget get _listView {
    return ListView(
      children: <Widget>[
        Container(
          height: 160,
          child: _banner,
        ),
        Padding(
          padding: EdgeInsets.fromLTRB(7, 4, 7, 4),
          child: LocalNav(localNavList: localNav),
        ),
        Padding(
          padding: EdgeInsets.fromLTRB(7, 4, 7, 4),
          child: GridNav(gridNavModel: gridNav),
        ),
        Padding(
          padding: EdgeInsets.fromLTRB(7, 4, 7, 4),
          child: SubNav(subNav: subNav,),
        ),
        SalesBox(salesBox: salesBox,)
      ],
    );
  }

  Widget get _banner {
    return Swiper(
      itemCount: bannerList.length,
      autoplay: true,
      itemBuilder: (BuildContext context, int index) {
        return Image.network(
          bannerList[index].icon,
          fit: BoxFit.cover,
        );
      },
      pagination: SwiperPagination(),
    );
  }

  Widget get _appBar {
    return Column(
      children: <Widget>[
        Container(
            decoration: BoxDecoration(
                gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [Color(0x66000000), Colors.transparent]
                )
            ),
            child: Container(
              padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
              height: 80,
              decoration: BoxDecoration(
                color: Color.fromARGB(
                    (_appBarAlpha * 255).toInt(), 255, 255, 255),
              ),
              child: SearchBar(
                searchBarType: _appBarAlpha > 0.2 ?
                SearchBarType.homeLeft : SearchBarType.home,
                inputBoxClick: _jumpToSearch,
                speakClick: () {},
                leftButtonClick: () {},
                defaultText: SEARCH_BAR_DEFAULT_TEXT,
              ),
            )
        ),
        Container(
            height: _appBarAlpha > 0.2 ? 0.5 : 0,
            decoration: BoxDecoration(
                boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 0.5)]))

      ],
    );
  }

  _jumpToSearch() {
    NavigatorUtil.push(context, SearchPage(
      hint: SEARCH_BAR_DEFAULT_TEXT,
    ));
  }
}